import { Button } from "antd";
import { useEffect, useState } from "react";

// 父组件
const OpenCommunicatingTab = (props) => {
  const [targetWindow, setTargetWindow] = useState(null);

  const openTab = () => {
    // 构建完整URL（包含当前域名和端口）
    // const baseUrl = `${location.protocol}//${location.hostname}${location.port ? `:${location.port}` : ''}`;
    // const fullUrl = new URL(path, baseUrl).toString();
    const newWindow = window.open('http://localhost:3001/#/admin/communicate-tab', '_blank');
    setTargetWindow(newWindow);
    
    // 发送初始化数据
    if (newWindow) {
      newWindow.postMessage(
        { type: 'INIT_DATA', data: { message: '来自父窗口的初始化数据' } },
        '*'
      );
    }
  };

  // 接收子窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      if (e.data.type === 'CHILD_RESPONSE') {
        console.log('子窗口响应:', e.data.payload);
        // 可以在这里处理子窗口返回的数据
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  // 向子窗口发送消息
  const sendToChild = () => {
    if (targetWindow) {
      targetWindow.postMessage(
        { type: 'PARENT_COMMAND', command: 'refreshData' },
        '*'
      );
    }
  };

  return (
    <div>
      <Button onClick={openTab}>打开可通信的新标签页</Button>
      <Button onClick={sendToChild} disabled={!targetWindow}>
        向子窗口发送命令
      </Button>
    </div>
  );
};

export default OpenCommunicatingTab;

// 子窗口组件
const CommunicateTab = () => {
  // 发送消息给父窗口
  const sendToParent = (data) => {
    window.opener?.postMessage(
      { type: 'CHILD_RESPONSE', payload: data },
      '*'
    );
  };

  // 接收父窗口消息
  useEffect(() => {
    const handleMessage = (e) => {
      if (e.data.type === 'INIT_DATA') {
        console.log('父窗口初始化数据:', e.data.data);
      } else if (e.data.type === 'PARENT_COMMAND') {
        console.log('父窗口命令:', e.data.command);
        if (e.data.command === 'refreshData') {
          // 执行刷新操作
          sendToParent({ status: 'refreshed', time: new Date() });
        }
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  return (
    <div>
      <h3>可通信的子标签页</h3>
      <Button onClick={() => sendToParent({ message: '来自子窗口的消息' })}>
        发送消息给父窗口
      </Button>
    </div>
  );
};
